package cn.ymatrix.utils;

import cn.ymatrix.service.ConnectService;
import cn.ymatrix.tableserver.TableService;
import com.alibaba.fastjson.JSONObject;
import org.apache.maven.shared.utils.StringUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;

public class BatchProcessingUtils {
    private static Connection conn = null;
    private static final BatchProcessingUtils batchProcessingUtils = new BatchProcessingUtils();
    static TableService ts = new TableService();
    static Integer index = 0;

    static StringBuffer ddlSQL = new StringBuffer();

    static StringBuffer ddldate = new StringBuffer();

    // 拼接数据
    public static void sqlTypeBatchSplicing(JSONObject jsonObj, int batchSize) throws Exception {
        try {
            index++;
            ddlSQL = ts.tableT1Service(jsonObj, batchSize);
            ddldate.append(ddlSQL);
            if (index == batchSize) {
                conn = DriverManager.getConnection(ConnectService.YMATRIX_URL, ConnectService.YMATRIX_USERNAME, ConnectService.YMATRIX_PASSWORD);
                //使用批处理 (获取数据源，拼装的sql，每500条提交一次)
                batchProcessingUtils.sqlBatchExecuteCanRollback(conn, ddldate.toString(), batchSize);
                // System.out.println("index--" + index);
                ddldate = new StringBuffer();
                index = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return boolean
     * @MethoName sqlBatchExecuteCanRollback
     * @Param [dataSource：获取数据源，sql：拼接好的sql语句, batchSize:多少次提交一次
     **/
    public boolean sqlBatchExecuteCanRollback(Connection connection, String ddlsql, int batchSize) throws Exception {

        if (StringUtils.isBlank(String.valueOf(ddlsql)) || ddlsql == null) {
            return false;
        }
        List<String> sqlList = Arrays.asList(ddlsql.split("-"));
        Statement statement = null;
        try {
            statement = connection.createStatement();
            connection.setAutoCommit(false);
            if (sqlList.size() <= batchSize) {
                for (int i = 0; i < sqlList.size(); i++) {
                    String s = sqlList.get(i);
                    statement.addBatch(s);
                }
                statement.executeBatch();
                connection.commit();
                return true;
            }
            if (sqlList.size() > batchSize) {
                for (int i = 0; i < sqlList.size(); i++) {
                    String s = sqlList.get(i);
                    statement.addBatch(s);
                    if (i != 0 && (i + 1) % batchSize == 0) {
                        statement.executeBatch();
                        statement.clearBatch();
                    }
                }
                statement.executeBatch();
                connection.commit();
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
                return false;
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            try {
                connection.close();
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

}
